package concurrent.c_001_Synchronized;

/**
 * synchronized 关键字，加锁
 */
public class T01_Lock {
    private int count = 10;
    private static int num = 10;
    private Object object = new Object();

    public void n() { // 访问这个方法的时候不需要上锁
        count++;
    }

    public void m1() {
        synchronized (object) { // 任何线程要执行下面的代码，必须先拿到 object 的锁
            count--;
            System.out.println(Thread.currentThread().getName() + " count = " + count);
        }
    }

    public void m2() {
        synchronized (this) { // 任何线程要执行下面的代码，必须先拿到 this 的锁
            count--;
            System.out.println(Thread.currentThread().getName() + " count = " + count);
        }
    }

    public synchronized void m3() { // 等同于在方法的代码执行时要 synchronized(this)
        count--;
        System.out.println(Thread.currentThread().getName() + " count = " + count);
    }

    public synchronized static void m4() { // 这里等同于 synchronized(T01_Lock.class)
        num--;
        System.out.println(Thread.currentThread().getName() + " count = " + num);
    }

    public static void m5() {
        synchronized (T01_Lock.class) { // 考虑一下这里写 synchronized(this) 是否可以？
            num--;
        }
    }
}